# Maintainer: Alexey Pavlov <alexpux@gmail.com>
# Maintainer: Ray Donnelly <mingw.android@gmail.com>

# Please keep this file exactly the same (except _variant=)
# as {mingw-w64-qt5/PKGBUILD,mingw-w64-qt5-static/PKGBUILD}
_variant=-static
#_variant=-shared

# The way Qt5 libraries are built. Possible values are '-release', '-debug' or '-debug-and-release'
_build_mode=-debug-and-release

# Tune the following to decide how and what to build
if [ "${_variant}" = "-static" ]; then
  _namesuff="-static"
  _with_icu=no
  _with_fontconfig=no
  _with_openssl=yes
  _with_dbus=yes
  _system_freetype=no
  _system_zlib=no
  _system_pcre=no
  _system_libpng=no
  _system_libjpeg=no
  _system_harfbuzz=no
  _build_examples=no # examples result in > 100 GiB
  _build_tools=yes
  _build_tests=yes
  _make_docs=no # docs in shared qt5 are sufficient
#  _ltcg="yes"
  _ltcg="no"
else
  _namesuff=
  _with_icu=yes
  _with_fontconfig=yes
  _with_openssl=yes
  _with_dbus=yes
  _system_freetype=yes
  _system_zlib=yes
  _system_pcre=yes
  _system_libpng=yes
  _system_libjpeg=yes
  _system_harfbuzz=yes
  _build_examples=yes
  _build_tools=yes
  _build_tests=yes
  _make_docs=yes
  _ltcg=no
fi

# Getting crashes that only happen in release builds?
# Define this and you may have a hope of figuring out
# why ..
_debuggable_release=no
#_debuggable_release=yes

# Using -O0 results in a Qt5WebKitd.dll that is > 2.5GB
# so force -Og. If you really need to, change this back
# to -O0, leave it blank or comment it out.
# Update: I think specifying anything here leads to huge
# Qt5WebKitd.dll, never commit with this set to anything
# -O0 is the default for GCC anyway, but qt5webkit seems
# to use a different flag if nothing explictly specified
# OPTIM_D="-Og"

# Thiago's patch doesn't contain the configure script changes
# needed, you may be able to get somewhere with this in the
# meantime (probably not though!)
if [ "${_ltcg}" = "yes" ]; then
   LTCG_CFLAGS="-flto-partition=1to1 -flto -ffat-lto-objects"
   LTCG_LFLAGS="-flto-partition=1to1 -flto -ffat-lto-objects"
fi

# So that both configure shell script and configure.exe
# are tested on MSYS2, we use both depending on variant
if [ "${_variant}" = "-static" ]; then
  _configure=./configure
else
  _configure=./configure.bat
fi

# When using the configure bash script, MSYS2 make is
# probably a better choice as otherwise the Makefiles
# can have MSYS2 paths in them. We try to handle this
# but it is ad-hoc at best.
if [ "${_configure}" = "./configure" ]; then
  _make=make
else
  _make=make
#  _make=${MINGW_PREFIX}/bin/mingw32-make
fi

#_opengl=angle
_opengl=desktop
#_opengl=dynamic
_opengl_for_configure="${_opengl}"

_realname=qt5${_namesuff}
pkgbase="mingw-w64-${_realname}"
pkgname="${MINGW_PACKAGE_PREFIX}-${_realname}"
_ver_base=5.10.1
# use 5.6.1-1 hot fix : only the archive name was changed from *-5.6.1.tar.xz to *-5.6.1-1.tar.xz
_hotfix=

# qt5-static must be kept in its own prefix hierarchy
# as otherwise it will conflict with qt5 itself
if [ "${_variant}" = "-static" ]; then
  _qt5_prefix="${MINGW_PREFIX}/${_realname}"
else
  _qt5_prefix="${MINGW_PREFIX}"
fi

pkgver=${_ver_base//-/}
pkgrel=2
arch=('any')
pkgdesc="A cross-platform application and UI framework (mingw-w64${_namesuff})"
url='https://www.qt.io/'
install=qt5-${CARCH}.install
license=('GPL3' 'LGPL' 'FDL' 'custom')
depends=("${MINGW_PACKAGE_PREFIX}-gcc-libs"
         "${MINGW_PACKAGE_PREFIX}-qtbinpatcher"
         $([[ "$_variant" == "-shared" ]] && echo \
            "${MINGW_PACKAGE_PREFIX}-assimp" \
            $([[ "$_with_dbus" == "yes" ]] && echo "${MINGW_PACKAGE_PREFIX}-dbus") \
            $([[ "$_with_fontconfig" == "yes" ]] && echo "${MINGW_PACKAGE_PREFIX}-fontconfig") \
            $([[ "$_system_freetype" == "yes" ]] && echo "${MINGW_PACKAGE_PREFIX}-freetype") \
            $([[ "$_system_harfbuzz" == "yes" ]] && echo "${MINGW_PACKAGE_PREFIX}-harfbuzz") \
            "${MINGW_PACKAGE_PREFIX}-jasper" \
            $([[ "$_system_libjpeg" == "yes" ]] && echo "${MINGW_PACKAGE_PREFIX}-libjpeg") \
            "${MINGW_PACKAGE_PREFIX}-libmng" \
            $([[ "$_system_libpng" == "yes" ]] && echo "${MINGW_PACKAGE_PREFIX}-libpng") \
            "${MINGW_PACKAGE_PREFIX}-libtiff" \
            "${MINGW_PACKAGE_PREFIX}-libxml2" \
            "${MINGW_PACKAGE_PREFIX}-libxslt" \
            "${MINGW_PACKAGE_PREFIX}-libwebp" \
            $([[ "$_with_openssl" == "yes" ]] && echo "${MINGW_PACKAGE_PREFIX}-openssl") \
            $([[ "$_system_pcre" == "yes" ]] && echo "${MINGW_PACKAGE_PREFIX}-pcre2") \
            "${MINGW_PACKAGE_PREFIX}-sqlite3" \
            "${MINGW_PACKAGE_PREFIX}-xpm-nox" \
            $([[ "$_system_zlib" == "yes" ]] && echo "${MINGW_PACKAGE_PREFIX}-zlib"))
            $([[ "$_opengl" != "desktop" ]] && echo "${MINGW_PACKAGE_PREFIX}-angleproject-git")
            $([[ "$_with_icu" == "yes" ]] && echo \
              "${MINGW_PACKAGE_PREFIX}-icu" \
              "${MINGW_PACKAGE_PREFIX}-icu-debug-libs")
        )

optdepends=($([[ "$_variant" == "-shared" ]] && echo \
            "${MINGW_PACKAGE_PREFIX}-libmariadbclient" \
            "${MINGW_PACKAGE_PREFIX}-firebird" \
            "${MINGW_PACKAGE_PREFIX}-postgresql")
           )
makedepends=("bison"
             "diffutils"
             "flex"
             "gperf"
             "m4"
             "make"
             "patch"
             "perl"
             "${MINGW_PACKAGE_PREFIX}-ruby"
             "${MINGW_PACKAGE_PREFIX}-gcc"
             "${MINGW_PACKAGE_PREFIX}-pkg-config"
             "${MINGW_PACKAGE_PREFIX}-python2"
             "${MINGW_PACKAGE_PREFIX}-make"
             "${MINGW_PACKAGE_PREFIX}-ninja"
             $([[ "$_variant" == "-static" ]] && echo \
               "${MINGW_PACKAGE_PREFIX}-dbus" \
               "${MINGW_PACKAGE_PREFIX}-openssl")
             $([[ "$_variant" == "-shared" ]] && echo \
               "${MINGW_PACKAGE_PREFIX}-libmariadbclient" \
               "${MINGW_PACKAGE_PREFIX}-firebird2" \
               "${MINGW_PACKAGE_PREFIX}-postgresql")
            )

groups=("${MINGW_PACKAGE_PREFIX}-qt${_namesuff}" "${MINGW_PACKAGE_PREFIX}-qt5${_namesuff}")
options=('!strip' 'staticlibs' 'ccache')
_pkgfqn="qt-everywhere-src-${_ver_base}"
noextract=(${_pkgfqn}${_hotfix}.tar.xz)
source=(#https://download.qt.io/development_releases/qt/${pkgver%.*}/${_ver_base//RC/rc}/single/${_pkgfqn}.tar.xz
        https://download.qt.io/official_releases/qt/${pkgver%.*}/${_ver_base}${_hotfix}/single/${_pkgfqn}${_hotfix}.tar.xz
        #https://download.qt.io/community_releases/${pkgver%.*}/${_ver_base}-final/qtwebkit-opensource-src-${_ver_base}.tar.xz
        #https://download.qt.io/snapshots/qt/${pkgver%.*}/${_ver_base}/2014-05-07_85/src/qt-everywhere-opensource-src-${_ver_base}.tar.xz
        0001-Add-link-time-optimization-support-for-Clang-GCC-and.patch
        0001-qt-5.8.0-fix-sql-libraries-mingw.patch
        0002-qt-5.8.0-configure-gcc-before-clang.patch
        0003-qt-5.8.0-autodetect-fontconfig.patch
        0005-qt-5.3.0-syncqt-fix.patch
        0006-qt-5.3.0-win_flex-replace.patch
        0007-qt-5.3.0-win32-g-Enable-static-builds.patch
        0008-qt-5.3.0-win32-g-Add-QMAKE_EXTENSION_IMPORTLIB-defaulting-to-.patch
        0009-qt-5.3.0-qmlimportscanner-Ensure-the-correct-variant-is-run.patch
        0010-qt-5.3.0-qdoc-increase-stack-size-for-win32-g-too.patch
        0011-qt-5.8.0-mingw-dbus-and-pkg-config.patch
        0016-qt-5.8.0-win32-g++-use-qpa-genericunixfontdatabase.patch
        0017-qt-5.3.0-fix-examples-building.patch
        0020-qt-5.3.0-use-external-angle-library.patch
        0023-qt-5.3.0-env-set-external-angle.patch
        0024-qt-5.3.0-icu-add-U_LIB_SUFFIX_C_NAME.patch
        0025-qt-5.8.0-force-using-make-on-msys.patch
        0028-qt-5.8.0-Revert-untangle-use-of-system-vs.-shell-path-list-se.patch
        0029-qt-5.8.0-Revert-fix-quoting-and-path-separators-in-qtPrepareT.patch
        0030-qt-5.3.1-workaround-ansidecl-h-PTR-define-conflict.patch
        0031-qt-5.5.0-workaround-BOOL-define-conflict.patch
        0034-qt-5.3.2-Use-QMAKE_PREFIX_STATICLIB-in-create_cmake-prf.patch
        0035-qt-5.3.2-dont-add-resource-files-to-qmake-libs.patch
        0036-qt-5.3.2-win32-qt5-static-cmake-link-ws2_32-and--static.patch
        0037-qt-5.4.0-Improve-cmake-plugin-detection-as-not-all-are-suffixed-Plugin.patch
        0038-qt-5.5.0-cmake-Rearrange-STATIC-vs-INTERFACE-targets.patch
        0039-qt-5.4.0-Make-it-possible-to-use-static-builds-of-Qt-with-CMa.patch
        0040-qt-5.4.0-Generate-separated-libraries-in-prl-files-for-CMake.patch
        0041-qt-5.4.0-Fix-mingw-create_cmake-prl-file-has-no-lib-prefix.patch
        0042-qt-5.4.0-static-cmake-also-link-plugins-and-plugin-deps.patch
        0043-qt-5.5.0-static-cmake-regex-QT_INSTALL_LIBS-in-QMAKE_PRL_LIBS_FOR_CMAKE.patch
        0044-qt-5.4.0-win32-g++-enable-qtwebengine-build.patch
        0045-qt-5.4.1-static-use-qminimal-platform-plugin-for-qcollectiongenerator.patch
        0046-qt-5.4.1-Revert-Revert-fix-NTFS-mount-points.patch
        0048-qt-5.4.2-win32-Avoid-platformNativeInterface-segfaults-with-minimal-platform.patch
        0049-qt-5.8.0-win32-do-not-use-fontconfig.patch
        0050-qt-5.5.1-fix-the-trailing-backslash-in-DESTDIR-on-mingw-worka.patch
        0051-qt-5.9.1-disable-qtlocation-mapboxgl-plugin.patch
        0125-qt5-windeployqt-fixes.patch
        0300-qt-5.8.0-cast-errors.patch
        qml_static_plugins.patch)

# Translates using cygpath according to the ${_make} being used
# (so either mingw32-make or MSYS2 make can be used)
path_conv_for_make() {
  if [ "${_make}" = "mingw32-make" ]; then
    echo -n "${1}" | sed "s|${MINGW_PREFIX}|$(cygpath -m ${MINGW_PREFIX})|g"
  else # MSYS2 make
    MINGW_PREFIX_W=$(cygpath -m ${MINGW_PREFIX})
    echo -n "${1}" | sed "s|${MINGW_PREFIX_W}|$(cygpath -u ${MINGW_PREFIX})|g"
  fi
}

# Runs pkg-config with all arguments, then calls path_conv_for_make on each
# result and then adds delimiter between -I/-L/-l and path - both configure
# and configure.bat prefer this. Results returned as an array.
pkg_config_qt5() {
  local _res=$(pkg-config $*)
  local -a _final=()
  for _part in $(path_conv_for_make "${_res}"); do
      _final+=($(echo -n "${_part}" | sed "s|-\([ILl]\)\(.*\)|-\1|g"))
      _final+=($(echo -n "${_part}" | sed "s|-\([ILl]\)\(.*\)|\2|g"))
  done
  echo "${_final[@]}"
}

prepare() {
  [[ -d ${srcdir}/${_pkgfqn} ]] && rm -rf ${srcdir}/${_pkgfqn}
  tar -xJf ${srcdir}/${_pkgfqn}${_hotfix}.tar.xz -C ${srcdir} --exclude=${_pkgfqn}/{qtandroidextras,qtmacextras,qtwayland,qtwebengine,qtx11extras} || true

  cd ${srcdir}/${_pkgfqn}

  # MSYS2 gperf cannot handle \r\n.
  find . -name "*.gperf" -exec dos2unix "{}" \;

  patch -p1 -i ${srcdir}/0001-qt-5.8.0-fix-sql-libraries-mingw.patch
  patch -p1 -i ${srcdir}/0002-qt-5.8.0-configure-gcc-before-clang.patch
  patch -p1 -i ${srcdir}/0003-qt-5.8.0-autodetect-fontconfig.patch
  patch -p1 -i ${srcdir}/0005-qt-5.3.0-syncqt-fix.patch
  patch -p1 -i ${srcdir}/0006-qt-5.3.0-win_flex-replace.patch

  # Some patches are against qtbase's repository.
  pushd qtbase > /dev/null
    patch -p1 -i ${srcdir}/0007-qt-5.3.0-win32-g-Enable-static-builds.patch
    patch -p1 -i ${srcdir}/0008-qt-5.3.0-win32-g-Add-QMAKE_EXTENSION_IMPORTLIB-defaulting-to-.patch
    ###patch -p1 -i ${srcdir}/0009-qt-5.3.0-qmlimportscanner-Ensure-the-correct-variant-is-run.patch
    #patch -p1 -i ${srcdir}/0010-qt-5.3.0-qdoc-increase-stack-size-for-win32-g-too.patch
    patch -p2 -i ${srcdir}/0011-qt-5.8.0-mingw-dbus-and-pkg-config.patch
    # The next patch needs some work. It's moving a block of shell script un-necessarily
    # as the bit: QMAKE_CONFIG="$QMAKE_CONFIG static" before calling compileTest is what
    # actually made it work. There may be a good reason for not adding static to QMAKE_CONFIG
    # so it might be necessary to back up the value, do compileTest then restore it after.
  popd > /dev/null

  patch -p1 -i ${srcdir}/0016-qt-5.8.0-win32-g++-use-qpa-genericunixfontdatabase.patch
  patch -p1 -i ${srcdir}/0017-qt-5.3.0-fix-examples-building.patch

  if [ "${_opengl}" != "desktop" ]; then
    # Hacks to use external ANGLE libraries.
    # These patches needs more work - they're unfinished and break desktop OpenGL
    patch -p1 -i ${srcdir}/0020-qt-5.3.0-use-external-angle-library.patch
    patch -p1 -i ${srcdir}/0023-qt-5.3.0-env-set-external-angle.patch
    if [ "${_configure}" = "./configure" ]; then
      _opengl_for_configure=yes
    fi
  fi

  # patch -p1 -i ${srcdir}/0024-qt-5.3.0-icu-add-U_LIB_SUFFIX_C_NAME.patch
  if [ "${_make}" = "make" ]; then
    patch -p1 -i ${srcdir}/0025-qt-5.8.0-force-using-make-on-msys.patch
  fi

  pushd qtbase > /dev/null
    # Ossi says we should fix this in qwebkit with a $$(shell_path), but the ' quotes get in the way
    # due to qtPrepareTool adding them with $$shell_quote
    patch -p1 -i ${srcdir}/0028-qt-5.8.0-Revert-untangle-use-of-system-vs.-shell-path-list-se.patch
    patch -p1 -i ${srcdir}/0029-qt-5.8.0-Revert-fix-quoting-and-path-separators-in-qtPrepareT.patch
    patch -p1 -i ${srcdir}/0030-qt-5.3.1-workaround-ansidecl-h-PTR-define-conflict.patch
  popd > /dev/null

  patch -p1 -i ${srcdir}/0031-qt-5.5.0-workaround-BOOL-define-conflict.patch
  patch -p1 -i ${srcdir}/0034-qt-5.3.2-Use-QMAKE_PREFIX_STATICLIB-in-create_cmake-prf.patch
  patch -p1 -i ${srcdir}/0035-qt-5.3.2-dont-add-resource-files-to-qmake-libs.patch

  # Patches so that qt5-static can be used with cmake.
  patch -p1 -i ${srcdir}/0036-qt-5.3.2-win32-qt5-static-cmake-link-ws2_32-and--static.patch
  patch -p1 -i ${srcdir}/0037-qt-5.4.0-Improve-cmake-plugin-detection-as-not-all-are-suffixed-Plugin.patch

  pushd qtbase > /dev/null
    patch -p1 -i ${srcdir}/0038-qt-5.5.0-cmake-Rearrange-STATIC-vs-INTERFACE-targets.patch
  popd

  patch -p1 -i ${srcdir}/0039-qt-5.4.0-Make-it-possible-to-use-static-builds-of-Qt-with-CMa.patch
  patch -p1 -i ${srcdir}/0040-qt-5.4.0-Generate-separated-libraries-in-prl-files-for-CMake.patch
  patch -p1 -i ${srcdir}/0041-qt-5.4.0-Fix-mingw-create_cmake-prl-file-has-no-lib-prefix.patch
  patch -p1 -i ${srcdir}/0042-qt-5.4.0-static-cmake-also-link-plugins-and-plugin-deps.patch
  patch -p1 -i ${srcdir}/0043-qt-5.5.0-static-cmake-regex-QT_INSTALL_LIBS-in-QMAKE_PRL_LIBS_FOR_CMAKE.patch

  # More odds and sods.
  # patch -p1 -i ${srcdir}/0044-qt-5.4.0-win32-g++-enable-qtwebengine-build.patch
  patch -p1 -i ${srcdir}/0045-qt-5.4.1-static-use-qminimal-platform-plugin-for-qcollectiongenerator.patch

  pushd qtbase > /dev/null
    patch -p1 -i ${srcdir}/0046-qt-5.4.1-Revert-Revert-fix-NTFS-mount-points.patch
  popd > /dev/null

  patch -p1 -i ${srcdir}/0048-qt-5.4.2-win32-Avoid-platformNativeInterface-segfaults-with-minimal-platform.patch
  patch -p1 -i ${srcdir}/0049-qt-5.8.0-win32-do-not-use-fontconfig.patch
  patch -p1 -i ${srcdir}/0051-qt-5.9.1-disable-qtlocation-mapboxgl-plugin.patch

  pushd qttools > /dev/null
    patch -p1 -i ${srcdir}/0125-qt5-windeployqt-fixes.patch
  popd
  
  patch -p1 -i ${srcdir}/0300-qt-5.8.0-cast-errors.patch

  # See: https://bugreports.qt.io/browse/QTBUG-37902
  # _ver_num=${_ver_base%%-*}
  # sed -i "s/^MODULE_VERSION = .*$/MODULE_VERSION = ${_ver_num}/g" qtenginio/.qmake.conf

  local _ARCH_TUNE=
  case ${MINGW_CHOST} in
    i686*)
      _ARCH_TUNE="-march=i686 -mtune=core2"
    ;;
    x86_64*)
      _ARCH_TUNE="-march=nocona -mtune=core2"
    ;;
  esac

  # Determine the CFLAGS, DEBUG_CFLAGS and LDFLAGS that we will tell qmake.conf about.
  # If this is qt5-static, we'd like to add -Os in an attempt to reduce size a little,
  # however there's an ICE in GCC 4.9.1 with x86_64, so must tread carefully.
  # https://gcc.gnu.org/bugzilla/show_bug.cgi?id=61207
  # Unlike OPTIM_D, please keep this one down here since it is not user selectable due
  # to the GCC bug.
  # This is the default, prevent re-appending.
  # OPTIM_O="-O2"
  if [ "${_variant}" = "-static" -a "${CARCH}" = "i686" ]; then
    OPTIM_O="-Os"
  fi

  if [ "${_debuggable_release}" = "yes" ]; then
    QMAKE_LFLAGS_RELEASE=
    OPTIM_O="${OPTIM_O} -g"
  else
    QMAKE_LFLAGS_RELEASE="-Wl,-s,--relax,--gc-sections"
    OPTIM_O="${OPTIM_O} -ffunction-sections -fdata-sections"
  fi

  BIGOBJ_FLAGS="-Wa,-mbig-obj"

  # Append these ones ..
  sed -i "s|^QMAKE_CFLAGS .*= \(.*\)$|QMAKE_CFLAGS            = \1 ${_ARCH_TUNE} ${BIGOBJ_FLAGS} ${LTCG_CFLAGS}|g" qtbase/mkspecs/win32-g++/qmake.conf
  if [ -n "$OPTIM_D" ]; then
    sed -i "s|^QMAKE_CFLAGS_DEBUG .*= \(.*\)$|QMAKE_CFLAGS_DEBUG      = \1 ${OPTIM_D}|g" qtbase/mkspecs/win32-g++/qmake.conf
  fi
  if [ -n "$OPTIM_O" ]; then
    sed -i "s|^QMAKE_CFLAGS_RELEASE .*= \(.*\)$|QMAKE_CFLAGS_RELEASE    = \1 ${OPTIM_O}|g" qtbase/mkspecs/win32-g++/qmake.conf
  fi
  sed -i "s|^QMAKE_LFLAGS            =\(.*\)$|QMAKE_LFLAGS            = \1 ${LTCG_LFLAGS}|g" qtbase/mkspecs/win32-g++/qmake.conf
  # But overwrite this one.
  sed -i "s|^QMAKE_LFLAGS_RELEASE .*= \(.*\)$|QMAKE_LFLAGS_RELEASE    = ${QMAKE_LFLAGS_RELEASE}|g" qtbase/mkspecs/win32-g++/qmake.conf

  # To keep the build folder name quite small (PATH_MAX limit)
  # the source folder (long) is renamed to $CARCH (i686 or x86_64)
  cd ${srcdir}
  [[ -d ${CARCH} ]] && rm -rf ${CARCH}
  sleep 5
  mv ${_pkgfqn} ${CARCH}
}

build() {
  local _buildpkgdir=${pkgdirbase}/${pkgname}/${_qt5_prefix}
  mkdir -p ${_buildpkgdir}
  local QTDIR_WIN=$(cygpath -am ${_buildpkgdir})

  local _freetype2_pkgconf=""
  if [ "$_system_freetype" == "yes" ]; then
    _freetype2_pkgconf="freetype2"
  fi

  local -a _extra_incpaths=($(pkg_config_qt5 --cflags-only-I dbus-1 libxml-2.0 ${_freetype2_pkgconf}))
  if [ "${_opengl}" != "desktop" ]; then
    export EXTERNAL_ANGLE=1
    _extra_incpaths+=("-I")
    _extra_incpaths+=("${MINGW_PREFIX}/include/GLSLANG")
  fi
  _extra_incpaths+=("-I")
  _extra_incpaths+=("${MINGW_PREFIX}/include/mariadb")

# This *could* be used but we'd have to make sure it's correct for all variants first.
#  local -a _extra_libpaths=($(pkg_config_qt5 --libs-only-L dbus-1 libxml-2.0 freetype2))
#  local -a _extra_libs=($(pkg_config_qt5 --libs-only-l dbus-1 libxml-2.0 freetype2))
  local -a _extra_libpaths=()
  local -a _extra_libs=()

  export PATH="${srcdir}/${CARCH}/qtbase/bin:${srcdir}/${CARCH}/qtbase/lib:${PATH}"

  if [ "${_variant}" = "-shared" ]; then
    # This export breaks the static library build in 5.9.0;
    # Causes the DBUS_LIBS setting passed to configure to be ignored.
    export PKG_CONFIG="${MINGW_PREFIX}/bin/pkg-config.exe"
  fi

  # Workaround for building QtWebkit
  #pushd ${srcdir}/${CARCH}/qtwebkit > /dev/null
  #  mkdir .git
  #  /usr/bin/perl ${srcdir}/${CARCH}/qtbase/bin/syncqt.pl Source -version ${pkgver}
  #  rm -rf .git
  #popd > /dev/null

  cd ${CARCH}
  touch qtbase/.gitignore

  # Set other config stuff that's configure-script-type dependent.
  local -a _extra_config
  if [ "${_configure}" = "./configure" ]; then
    _extra_config+=("-no-glib")
  else
    _extra_config+=("-make-tool")
    _extra_config+=("${_make}")
  fi

  # Determine the SQL driver configuration, variant dependent.
  # static can't use anything but -qt-sql-sqlite both for size
  # reasons and because shared libraries get auto-detected and
  # built as plugins.
  local -a _sql_config
  if [ "${_variant}" = "-static" ]; then
    _sql_config+=("-no-sql-ibase")
    _sql_config+=("-no-sql-mysql")
    _sql_config+=("-no-sql-odbc")
    _sql_config+=("-no-sql-psql")
    _sql_config+=("-no-sql-sqlite2")
    _sql_config+=("-sql-sqlite")
    _sql_config+=("-qt-sqlite")
  else
    _sql_config+=("-plugin-sql-ibase")
    _sql_config+=("-plugin-sql-psql")
    _sql_config+=("-plugin-sql-mysql")
    _sql_config+=("-plugin-sql-odbc")
    _variant_CPATH=${MINGW_PREFIX}/include/mariadb:
  fi

  if [ "${_variant}" = "-static" ]; then
    export OPENSSL_LIBS="-lssl -lcrypto -lcrypt32 -lgdi32"
  fi

  # Qt manages the compiler flags for release / debug configs separately, so having our own values (-O2) is harmful here ..
  unset CFLAGS
  unset CXXFLAGS
  unset LDFLAGS
  unset QMAKESPEC
  unset XQMAKESPEC
  unset QMAKEPATH
  unset QMAKEFEATURES
# export NINJA_PATH=${MINGW_PREFIX}/bin/ninja.exe

  local -a configure_opts

  if [ "${_variant}" = "-static" ]; then
    configure_opts+=("-static")
    configure_opts+=("-D" "DBUS_STATIC_BUILD")
    configure_opts+=("-D" "JAS_DLL=0")
    if [ "$_with_dbus" == "yes" ]; then
      configure_opts+=("-dbus-linked" "DBUS_LIBS=-ldbus-1 -lws2_32 -liphlpapi")
    else
      configure_opts+=("-no-dbus")
    fi
    if [ "$_with_openssl" == "yes" ]; then
      configure_opts+=("-openssl-linked")
    else
      configure_opts+=("-no-openssl")
    fi
  else
    configure_opts+=("-shared")
    if [ "$_with_dbus" == "yes" ]; then
      configure_opts+=("-dbus")
    else
      configure_opts+=("-no-dbus")
    fi
    if [ "$_with_openssl" == "no" ]; then
      configure_opts+=("-no-openssl")
    fi
  fi

  if [ "$_with_fontconfig" == "no" ]; then
    configure_opts+=("-no-fontconfig")
  fi
  if [ "$_system_freetype" == "yes" ]; then
    configure_opts+=("-system-freetype")
  else
    configure_opts+=("-qt-freetype")
  fi
  if [ "$_system_harfbuzz" == "yes" ]; then
    configure_opts+=("-system-harfbuzz")
  else
    configure_opts+=("-qt-harfbuzz")
  fi
  if [ "$_system_libjpeg" == "no" ]; then
    configure_opts+=("-qt-libjpeg")
  fi
  if [ "$_system_libpng" == "no" ]; then
    configure_opts+=("-qt-libpng")
  fi
  if [ "$_system_zlib" == "no" ]; then
    configure_opts+=("-qt-zlib")
  fi
  if [ "$_system_pcre" == "no" ]; then
    configure_opts+=("-qt-pcre")
  fi
  if [ "$_with_icu" == "yes" ]; then
    configure_opts+=("-icu")
  else
    configure_opts+=("-no-icu")
  fi
  if [ "$_build_examples" == "no" ]; then
    configure_opts+=("-nomake" "examples")
  fi
  if [ "$_build_tests" == "no" ]; then
    configure_opts+=("-nomake" "tests")
  fi
  if [ "$_build_tools" == "no" ]; then
    configure_opts+=("-skip" "qttools")
  fi

  ${_configure} \
    -prefix ${QTDIR_WIN} \
    -datadir ${QTDIR_WIN}/share/qt5 \
    -archdatadir ${QTDIR_WIN}/share/qt5 \
    -examplesdir ${QTDIR_WIN}/share/qt5/examples \
    -testsdir ${QTDIR_WIN}/share/qt5/tests \
    -opengl ${_opengl_for_configure} \
    -opensource \
    -confirm-license \
    -platform win32-g++ \
    "${_build_mode}" \
    "${_extra_incpaths[@]}" \
    "${_extra_libpaths[@]}" \
    "${_extra_libs[@]}" \
    -no-iconv \
    -no-gstreamer \
    "${_extra_config[@]}" \
    "${_sql_config[@]}" \
    "${configure_opts[@]}"

  # I'm keeping this around while qt5-static cmake problems persist (hopefully not long!)
  # qtbase/mkspecs/modules-inst/qt_lib_core.pri
  # pushd src/x86_64
  #   ROOT=$(pwd -W)
  #   pushd qtbase/
  #     ${ROOT}/qtbase/bin/qmake.exe ${ROOT}/qtbase/qtbase.pro -o Makefile
  #   popd
  #   cp -rf qtbase/src/corelib qtbase/src/corelib.pre-write-cmake
  #   pushd qtbase/src/corelib
  #     ${ROOT}/qtbase/bin/qmake.exe ${ROOT}/qtbase/src/corelib/corelib.pro -d -d -d -d -o Makefile > log.txt
  #   popd
  # popd
  # .
  # .. or .. (this alternative could be used when _minimal=yes)
  # .
  # pushd src/x86_64
  #   ${_make} module-qtbase && ${_make} module-qtbase-install_subtargets
  # popd
  # .. do your testing.
  # There is a race condition / dependency problem with libqtiff and dumpdoc.exe which
  # can happen at -j9 so make twice (dumpdoc.exe depends on libqtiff but can get built
  # first).
  ${_make} ${MAKEFLAGS} || ${_make} ${MAKEFLAGS}
  # For quicker turn-around testing qtwebengine.
  # ${_make} module-qtbase
  # ${_make} module-qtwebengine
  # exit 1

  # Fix paths
  # find "${QTDIR}" -name Makefile -exec sed -i "s|/usr/lib/qt/bin/qdoc|${QTDIR}/qtbase/bin/qdoc|g" {} +
  # find "${QTDIR}" -name Makefile.qmake-docs -exec sed -i "s|/usr/lib/qt/bin/qdoc|${QTDIR}/qtbase/bin/qdoc|g" {} +
  # find "${QTDIR}" -name Makefile -exec sed -i "s|/usr/lib/qt/bin/qhelpgenerator|${QTDIR}/qttools/bin/qhelpgenerator|g" {} +
  # find "${QTDIR}" -name Makefile.qmake-docs -exec sed -i "s|/usr/lib/qt/bin/qhelpgenerator|${QTDIR}/qttools/bin/qhelpgenerator|g" {} +
  # sed -i "s|/usr/lib/qt/bin/qhelpgenerator|${QTDIR}/qttools/bin/qhelpgenerator|g" qtwebkit/Source/Makefile.api
}

check() {
  cd ${CARCH}
  make check -j1 -k
}

package() {

  cd ${CARCH}

  export PATH=${pkgdir}${_qt5_prefix}/bin:${srcdir}/${CARCH}/qtbase/bin:${srcdir}/${CARCH}/qtbase/lib:${PATH}

  ${_make} install
  if [ "$_make_docs" == "yes" ]; then
    make docs
    make install_qch_docs
  fi

  install -D -m644 LGPL_EXCEPTION.txt \
    "${pkgdir}${_qt5_prefix}"/share/licenses/qt5/LGPL_EXCEPTION.txt

  # Remove dlls from lib/
  rm -f "${pkgdir}${_qt5_prefix}/lib"/*.dll

  # Workaround for installing empty .pc files
  plain "---> Fix pkgconfig files..."
  local _pc_files=( $(find ${srcdir}/${CARCH} -type f -name Qt5*.pc) )
  cp -f ${_pc_files[@]} ${pkgdir}${_qt5_prefix}/lib/pkgconfig/

  # Fix wrong path in prl files
  # find "${pkgdir}${_qt5_prefix}/lib" -type f -name '*.prl' \
  #   -exec sed -i -e '/^QMAKE_PRL_BUILD_DIR/d;s/\(QMAKE_PRL_LIBS =\).*/\1/' {} \;

  # Fix wrong qmake path in pri file
  # sed -i "s|${srcdir}/${CARCH}/qtbase|/usr|" \
  #   "${pkgdir}"/usr/lib/qt/mkspecs/modules/qt_lib_bootstrap_private.pri

  # Fix paths in qconfig.pri and qmodule.pri:
  #   $(cygpath -m ${MINGW_PREFIX}) -> $(cygpath -m ${pkgdir}${MINGW_PREFIX})
  MINGW_PREFIX_WIN=$(cygpath -m ${_qt5_prefix})
  PKGDIR_MINGW_PREFIX_WIN=$(cygpath -m ${pkgdir}${_qt5_prefix})
  find "${pkgdir}${_qt5_prefix}/share/qt5" -type f -name '*.pri' \
    -exec sed -i -e "s|${MINGW_PREFIX_WIN}|${PKGDIR_MINGW_PREFIX_WIN}|g" {} \;

  # https://github.com/Alexpux/MINGW-packages/issues/1942
  if [ "${_variant}" = "-static" ]; then
    cd ${pkgdir}${_qt5_prefix}
    patch -p1 -i ${srcdir}/qml_static_plugins.patch
    rm -v "lib/cmake/Qt5Gui/Qt5Gui_QVirtualKeyboardPlugin.cmake"
  fi
}

# return 0
# And now for something completely broken:
# https://bugreports.qt.io/browse/QTBUG-40814
# Using this:
# https://www.mirrorservice.org/sites/download.qt-project.org/snapshots/qt/5.3/5.3.2/2014-09-12_151/qt-opensource-windows-x86-msvc2013_64-5.3.2_2014-09-12_10-11-49-151.exe
# and:
# https://www.mirrorservice.org/sites/download.qt-project.org/snapshots/qt/5.3/5.3.2/2014-09-12_src/qt-everywhere-opensource-src-5.3.2.zip
# ..  unpacked into C:\work\build\qt5_workdir\w\s
# On MinGW-w64, both debug and release fail .. release has an extra segfault though quite early on.
# pushd /e/m2/repo/mingw-w64-qt5/src/x86_64/qtscript/tests
# export PATH=/mingw64/bin:$PATH
# export PKG_CONFIG_PATH=/mingw64/lib/pkgconfig
# for CONFIG in debug release; do
#   [ -d ${CONFIG} ] && rm -rf ${CONFIG}
#   mkdir ${CONFIG}
#   pushd ${CONFIG}
#   qmake -r CONFIG+=${CONFIG} ../
#   make -j12
#   ls -l ./auto/qscriptjstestsuite/${CONFIG}/tst_qscriptjstestsuite.exe    > qscriptjstestsuite.log
#   ./auto/qscriptjstestsuite/${CONFIG}/tst_qscriptjstestsuite.exe -silent >> qscriptjstestsuite.log
#   popd
# done

# i686 build failure with yarr:
# export PATH=/mingw32/bin:$PATH
# export PKG_CONFIG_PATH=/mingw32/lib/pkgconfig
# pushd /e/m2/repo/mingw-w64-qt5/src/i686/qtdeclarative/src/qml
# make
# make[4]: Entering directory '/e/m2/repo/mingw-w64-qt5/src/i686/qtdeclarative/src/qml'
# g++ -Wl,-s -shared -Wl,--out-implib,E:/m2/repo/mingw-w64-qt5/src/i686/qtdeclarative/lib/libQt5Qml.dll.a -o ../../lib/Qt5Qml.dll object_script.Qt5Qml.Release  -lshell32 -LE:/m2/repo/mingw-w64-qt5/src/i686/qtbase/lib -lQt5Network -lQt5Core .obj/release/Qt5Qml_resource_res.o
# ./.obj/release/YarrInterpreter.o:YarrInterpreter.cpp:(.text+0x622): undefined reference to `JSC::Yarr::wordcharCreate()'
# ./.obj/release/YarrInterpreter.o:YarrInterpreter.cpp:(.text+0x693): undefined reference to `JSC::Yarr::newlineCreate()'
# E:/msys64/mingw32/bin/../lib/gcc/i686-w64-mingw32/4.9.1/../../../../i686-w64-mingw32/bin/ld.exe: ./.obj/release/YarrInterpreter.o: bad reloc address 0x12 in section `.text$_ZN3WTF15BumpPointerPool6createEj[__ZN3WTF15BumpPointerPool6createEj]'
# collect2.exe: error: ld returned 1 exit status
# Makefile.Release:534: recipe for target '../../lib/Qt5Qml.dll' failed

# pushd /e/m2/repo/mingw-w64-qt5/src/i686/qtdeclarative/src/qml
# export PATH=/mingw32/bin:$PATH
# export PKG_CONFIG_PATH=/mingw32/lib/pkgconfig
# E:/m2/repo/mingw-w64-qt5/src/i686/qtbase/bin/qmake.exe -o Makefile qml.pro

sha256sums=('05ffba7b811b854ed558abf2be2ddbd3bb6ddd0b60ea4b5da75d277ac15e740a'
            '7363ae7695af2f5278e9d91f6e52b3533dea4139ef252284bb82abfd025630d9'
            '70938426942058ad66c1b9b304b12cfe7a85947712729a9b7235c86397cfc265'
            '52a8c1ac8511643a10eb9b3b80b6881ecb3d08d4b5b9b730d16da461a40c4aa6'
            '91b9e23592cc1042fde7ee43a828be695da91c5575803924897eac2a3bef8853'
            '334e8f84b892e1bda5d71ec078d6e2a325d979f0d3ab454fe348594d1c039f84'
            '1b615ac7425fb7dc81d072f4c48e96d6fe0df5dcdeced61341aa3ca44c365e2b'
            '1d8ac1807437f2ac6fa7b25e173c3ca69dd32381e5b2fa501499f96972ad1d2e'
            'b21726bbd2ed34ad78e18d6b82a2c3b3c3e753ee2e978a5bb58b386f1f33ce41'
            '3dd3ca4cb60adbc6af636151460f1c51da8535d37a8f6c32948afca7858986b2'
            '8ce3f884cce4cf0b00fbb149d3acf73a664c9ef330325ba95d15846ef18f9aa2'
            '66b6c6dac6b3c208d5930d12602e0d4a714d72fb881a5792bf966c0c46ab5aa9'
            '10dc3177cf7c76667e28fee51dc3b029ba1f0eff16901672b39250177fa20663'
            'e24f642a18a8dc547caa3029f39a562405aac88bc573d3cd5ef502a423486067'
            'e0e029c97ebe41abdcbb2beec779b75657c1ecc15e0211d5db69111a3750268d'
            'd0dbe4b5f8a9291a02f9e9c6e59a0ff038e5dc521f79eb2da7a5fcaa681479bb'
            'd7c228df3cc680793a6c858e1fac01092c0877071c075804b7e93f6b3a481eae'
            '493c081dd06836baa28cac1f38b2d87b2f402670e442b8a163530d3f965cc5e1'
            '4cad37e9cf4d0777fe614b37c799cbeb9b953cd6a6bc38c5b52a2557614aaf39'
            '42e5ebc4bc785bfa50262047ae5078bc123f56e9129a1df0b2f84491f75d886c'
            '6893c83e4d26643a1cf5607a1a367401d27fec98440fa1d3685a8cf1478ddf92'
            '7f5e092a5062db776a96ab32758ff175c3689b79902f5d9656f31029c33f66dd'
            '1ada266bc6cd033d770bc40ad879527db222563fc20cf98cf2848b84b2a0e503'
            '27e9d402126d313ff647066207038578c26a3cf0f60833ae5d76157d53712eae'
            '29f13f7b44476bebfc5280a8481fa24926185860476ed0fd05f6b5a959b801d8'
            'c114d2df071b66e47f4bd43d335d48868fd5bcf9670f276b557edacd53fa92c0'
            'b9939efea7792a960cdc9404a515c6f0a1cd42ffbdb018d52f2b0206fffe17f5'
            '3ae9d64fb683036b3b1f91036378791e1ec4a10205c59e78761d22d8479c0540'
            'd720ac76035d56caea1f045dfb468a25865f9d4b22016cec5414f1c639a7697a'
            '914051840e01bf453e3db710d4471e6758e39e2cb87f8ffe3072fb90218c9f83'
            'f5454bc38d57a734e5b36f6c54310576339628298d810628443f0a58a46e7477'
            '29ed4566d4c1853b70a5173c6391ed90f123c5121b5836f2d16f8478f6354f0a'
            '7d7a99ff45c6ae4f39be663d52bafc125970787f364e84593117e6a7d79f7eae'
            '72e46178f2f694d8408f22684d1a7d39394056cb574fc4855c1f38c9d51e7e6c'
            '57730800c740c0609739c141283494748b34643b1af0504bf5ba8767b8655557'
            '3bda25f357a33b122345fea011a14199b5953fd248fab960a5344a2ed9401331'
            'ca5a67f795f04ed0831dc6084affc3553b22ea9b6af6c11c15871415c81f6a04'
            '234d1b207eb9ea11839f941799daf613028f33dbc89bebdf78b9a2dd4dd84dd2'
            '227940744aa3d87f51d9ea9d2fff0bfc11cda5f5055687bceb1c93ade5d5cdf6'
            '353afa72d5f659213625d1af02653308ead2a74292023cc960b55f04d6a098af'
            'a709aca42e8aa634a9a9d6ded96331635ae1198cc805ff632bbc05254aaf180d'
            '670161ba661ea3dccd883473e39aaecb683a3c92da73502dc6939d496507532c')
